package com.dt.record

import android.R.attr.path
import android.annotation.SuppressLint
import android.content.Context
import android.icu.text.SimpleDateFormat
import android.media.MediaMetadataRetriever
import android.os.Environment
import android.os.Handler
import android.os.SystemClock
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.Toast
import android.widget.VideoView
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.util.*


class VideoControl(videoView: VideoView, fullWin: MainActivity){
    private var videoDir= Environment.getExternalStorageDirectory().path+"/CCTV"
    private var videoName=""
    private var stopFlag = false   //区分是否已经停止播放
    private var seekBarPressed=false
    private val mfullWin=fullWin
    private var zoomVal=1.0f
    private lateinit var layoutParams: RelativeLayout.LayoutParams
    private var xDelta:Int = 0
    private var yDelta:Int = 0
    private var heightDefault = 0
    private var widthDefault = 0
    private val mFullHandler = Handler()
    private val mFullRunnable = Runnable { fullScream() }

    //界面
    private val background=fullWin.bg_view
    private val fileMenu_view=fullWin.file_control
    private val videoMenu_view=fullWin.fullscreen_content_controls
    private val mVideolayout=fullWin.videoLayout
    private val mVideoView=videoView
    private val button_play=fullWin.button_play
    private val button_play1=fullWin.button_play1
    private val button_play2=fullWin.button_play2
    private val button_stop=fullWin.button_stop
    private val button_full=fullWin.button_full
    private val seekBar=fullWin.seekBar
    private val runTime=fullWin.runtime
    private val endTime=fullWin.endtime

    private val button_zoomAdd=null
    private val button_zoomSub=null

    private val mDelayFullTouchListener = View.OnTouchListener { _, _ ->
        delayedFull(200)
        false
    }

    val gestureDetector = GestureDetector(
        mVideoView.context,
        object : GestureDetector.SimpleOnGestureListener() {

            override fun onDown(e: MotionEvent?): Boolean {
                return true
            }

            /**
             * 发生确定的单击时执行
             * @param e
             * @return
             */
            override fun onSingleTapConfirmed(e: MotionEvent?): Boolean { //单击事件

//                Toast.makeText(mVideoView.context, "这是单击事件", Toast.LENGTH_SHORT).show()
                fullWin.toggle()
                return super.onSingleTapConfirmed(e)
            }

            /**
             * 双击发生时的通知
             * @param e
             * @return
             */
            override fun onDoubleTap(e: MotionEvent?): Boolean { //双击事件
//                Toast.makeText(mVideoView.context, "这是双击事件", Toast.LENGTH_SHORT).show()
                if (button_play.tooltipText == "start") {
                    button_play.tooltipText = "pause"

                    start()

                } else {
                    button_play.tooltipText = "start"

                    pause()

                }
                return super.onDoubleTap(e)
            }

            /**
             * 双击手势过程中发生的事件，包括按下、移动和抬起事件
             * @param e
             * @return
             */
            override open fun onDoubleTapEvent(e: MotionEvent?): Boolean {
                return super.onDoubleTapEvent(e)
            }
        })

    private val handler = Handler()
    private val runnable: Runnable = object : Runnable {
        override fun run() {
            if (mVideoView.isPlaying and !seekBarPressed) {
                val current = 100*mVideoView.currentPosition/mVideoView.duration
                seekBar.progress = current
                runTime.text=time(mVideoView.currentPosition)

            }
            handler.postDelayed(this, 200)
        }
    }


//    private val xDefault:Int
//    private val yDefault:Int

    init {
//        val lParams = mVideoView.getLayoutParams() as RelativeLayout.LayoutParams
//        xDefault= lParams.leftMargin
//        yDefault= lParams.topMargin
        mVideoView.setOnPreparedListener {
            //视频加载完成,准备好播放视频的回调
        }
        mVideoView.setOnCompletionListener {  //视频播放完成后的回调
            button_play.tooltipText = "start"
            button_play.setImageDrawable(
                mfullWin.resources.getDrawable(
                    android.R.drawable.ic_media_play,
                    null
                )
            )
            button_play2.setImageDrawable(
                mfullWin.resources.getDrawable(
                    android.R.drawable.ic_media_play,
                    null
                )
            )
            button_play1.visibility = View.VISIBLE


        }
        mVideoView.setOnErrorListener { mp, what, extra ->
            //异常回调
            false //如果方法处理了错误，则为true；否则为false。返回false或根本没有OnErrorListener，将导致调用OnCompletionListener。
        }
        mVideoView.setOnInfoListener { mp, what, extra ->

            when (what) {
                1 ->
                    Log.w("VideoView", "MEDIA INFO UNKNOWN")
                3 ->
                    Log.i("VideoView", "MEDIA INFO VIDEO RENDERING START")
                700 ->
                    Log.w("VideoView", "MEDIA INFO VIDEO TRACK LAGGING")
                701 ->
                    Log.i("VideoView", "MEDIA INFO BUFFERING START")
                702 ->
                    Log.i("VideoView", "MEDIA INFO BUFFERING END")
                703 ->
                    Log.i("VideoView", "MEDIA INFO NETWORK BANDWIDTH")
                800 ->
                    Log.w("VideoView", "MEDIA INFO BAD INTERLEAVING")
                801 ->
                    Log.w("VideoView", "MEDIA INFO NOT SEEKABLE")
                802 ->
                    Log.i("VideoView", "MEDIA INFO METADATA UPDATE")
                901 ->
                    Log.w("VideoView", "MEDIA INFO UNSUPPORTED SUBTITLE")
                902 ->
                    Log.w("VideoView", "MEDIA INFO SUBTITLE TIMED OUT")
                else ->
                    Log.e("VideoView", "UNKONW INFO")

            }
            //信息回调
            //                what 对应返回的值如下
            //                public static final int MEDIA_INFO_UNKNOWN = 1;  媒体信息未知
            //                public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; 媒体信息视频跟踪滞后
            //                public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3; 媒体信息\视频渲染\开始
            //                public static final int MEDIA_INFO_BUFFERING_START = 701; 媒体信息缓冲启动
            //                public static final int MEDIA_INFO_BUFFERING_END = 702; 媒体信息缓冲结束
            //                public static final int MEDIA_INFO_NETWORK_BANDWIDTH = 703; 媒体信息网络带宽（703）
            //                public static final int MEDIA_INFO_BAD_INTERLEAVING = 800; 媒体-信息-坏-交错
            //                public static final int MEDIA_INFO_NOT_SEEKABLE = 801; 媒体信息找不到
            //                public static final int MEDIA_INFO_METADATA_UPDATE = 802; 媒体信息元数据更新
            //                public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901; 媒体信息不支持字幕
            //                public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902; 媒体信息字幕超时
            false //如果方法处理了信息，则为true；如果没有，则为false。返回false或根本没有OnInfoListener，将导致丢弃该信息。
        }

        heightDefault = mVideolayout.layoutParams.height
        widthDefault = mVideolayout.layoutParams.width

//        mVideoView.currentPosition

//        provider_init()
//        button_full.setOnTouchListener(this.mDelayFullTouchListener)
        mVideoView.setOnTouchListener({ v, event -> gestureDetector.onTouchEvent(event) })

        /**
         * 监听进度条
         */
        seekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
//                Log.i("seekBar", "seekbar progress: $progress")
//                Log.i("seek","time"+mVideoView.duration.toString())
                val buf = time(mVideoView.duration * seekBar.getProgress() / 100)
                runTime.text = buf
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
//                Log.i("seekBar","seekbar touch started!")
                seekBarPressed = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {

//                Log.i("seekBar","seekbar touch stopped!")
                val progress = seekBar.getProgress()
                mVideoView.seekTo((progress * mVideoView.duration) / 100)

                val buf = time(mVideoView.currentPosition)/* / 60000) + ":" + String.format(
                        "%02d",
                        (mVideoView.currentPosition / 1000) % 60

                    )*/
                runTime.text = buf
                seekBarPressed = false

            }
        })


    }

    protected fun time(millionSeconds: Int): String? {

        val simpleDateFormat = if(millionSeconds >= 3600000) SimpleDateFormat("mmm:ss")
                                                                        else SimpleDateFormat("mm:ss")
        val c = Calendar.getInstance()
        c.timeInMillis = millionSeconds.toLong()
        return simpleDateFormat.format(c.time)
    }

    /**
    选中播放文件
     */
    fun setVideoFile(name: String){
        videoName=name
        val file = File(videoDir, videoName)
//            Log.i("fileDir---",Environment.getExternalStorageDirectory().path)
        if (!file.exists()) {
            Toast.makeText(mVideoView.context, "视频不存在", Toast.LENGTH_SHORT).show()
            //              mfullWin.finish() //释放当前activity,在下一个activity按下返回键不会回到当前activity,直接跳到此activity的上一个activity
            return
        }

        mVideoView.setVideoPath(file.getAbsolutePath()) //设置视频文件
        stopFlag=false //表示已加载播放文件

        val mmr = MediaMetadataRetriever()
        mmr.setDataSource(videoDir+videoName)
        endTime.text=time(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION).toInt())

    }
    fun reflashTime(): String? {
        endTime.text=time(mVideoView.duration)
        return time(mVideoView.duration)
    }
    fun setVideoDir(directory: String){
//        videoDir=directory
    }
    fun runState():Boolean{ return !stopFlag }

    private fun delayedFull(delayMillis: Int) {
        mFullHandler.removeCallbacks(mFullRunnable)
        mFullHandler.postDelayed(mFullRunnable, delayMillis.toLong())
    }

    fun start() {
        Log.i(
            "seek2",
            "time" + time(mVideoView.duration)
        )

        if (stopFlag) {
            setVideoFile(videoName)
            mVideoView.start()
        }else
            mVideoView.start()
        button_play.setImageDrawable(
            mfullWin.resources.getDrawable(
                android.R.drawable.ic_media_pause,
                null
            )
        )
        button_play2.setImageDrawable(
            mfullWin.resources.getDrawable(
                android.R.drawable.ic_media_pause,
                null
            )
        )
        button_play1.visibility = View.GONE


        handler.postDelayed(runnable, 0)//刷新进度条

    }
    fun start_view(){

    }
    fun full_view(){
    }

    fun pause(){
        mVideoView.pause()
        button_play.setImageDrawable(
            mfullWin.resources.getDrawable(
                android.R.drawable.ic_media_play,
                null
            )
        )//修改播放按键图标
        button_play2.setImageDrawable(
            mfullWin.resources.getDrawable(
                android.R.drawable.ic_media_play,
                null
            )
        )//修改播放按键图标
        button_play1.visibility = View.VISIBLE
    }

    fun stop(){
        seekBar.progress = 100
        runTime.text=time(mVideoView.duration)

        mVideoView.stopPlayback()
        button_play.setImageDrawable(
            mfullWin.resources.getDrawable(
                android.R.drawable.ic_media_play,
                null
            )
        )//修改播放按键图标
        button_play2.setImageDrawable(
            mfullWin.resources.getDrawable(
                android.R.drawable.ic_media_play,
                null
            )
        )//修改播放按键图标
        button_play1.visibility = View.VISIBLE
        stopFlag = true
        handler.removeCallbacks(runnable)//停止进度条刷新

    }

    @SuppressLint("ResourceAsColor")
    fun fullScream(){

        val heightNew=mVideolayout.layoutParams.height
        val widthNew=mVideolayout.layoutParams.width
        val dm = DisplayMetrics()
        mfullWin.windowManager.defaultDisplay.getRealMetrics(dm)

        if(button_full.tooltipText == "full") {
            background.background=background.resources.getDrawable(R.color.black_overlay)//切换背景颜色
            Log.i("fullScream", "full")
            for( iCount in 10 until  dm.heightPixels-heightNew step 10){
                mVideolayout.layoutParams.height = iCount +heightNew
                mVideolayout.layoutParams.width = iCount +widthNew
                mVideolayout.requestLayout()//刷新view
                SystemClock.sleep(20)
            }

            mVideolayout.layoutParams.height = dm.heightPixels
            mVideolayout.layoutParams.width = dm.widthPixels
            button_full.tooltipText = "window"
            fileMenu_view.visibility = View.GONE
            videoMenu_view.visibility = View.VISIBLE


            /**
             *  val layoutParams = mVideoView.getLayoutParams() as RelativeLayout.LayoutParams
            layoutParams.leftMargin = 500
            layoutParams.topMargin = 500
            mVideoView.setLayoutParams(layoutParams) //自己继承VIEW的this*/
        }else{
            background.background=background.resources.getDrawable(R.color.coloCyan)//切换背景颜色
            Log.i("fullScream", "window")
            for( iCount in 10 until  heightNew-heightDefault step 10){
                mVideolayout.layoutParams.height = heightNew -iCount
                mVideolayout.layoutParams.width = widthNew -iCount
                mVideolayout.requestLayout()//刷新view
                SystemClock.sleep(20)
            }
            mVideolayout.layoutParams.height = heightDefault
            mVideolayout.layoutParams.width = widthDefault
            button_full.tooltipText = "full"
            fileMenu_view.visibility = View.VISIBLE
            videoMenu_view.visibility = View.GONE
//            background.setBackgroundColor(0x99cccc) //会导致背景残影
//            background.setBackgroundColor(R.color.coloCyan)

        }
        mVideolayout.requestLayout()//刷新view(马上全屏显示)
//        background.requestLayout()

//        mVideoView.measure(mfullWin.windowManager.defaultDisplay.width,mfullWin.windowManager.defaultDisplay.height)
    }
    /**
     *
     * zoomAndMove()用于将视窗放大缩小或移动
     *
     * */
    fun zoomAndMove(zFlag: Char, mX: Int, mY: Int){

        when(zFlag) {
            '+' ->  //放大视窗
                if (zoomVal < 5)
                    zoomVal += 0.05f
            '-' ->   //缩小视窗
                if (zoomVal > 1)
                    zoomVal -= 0.05f

            else ->{//移动视窗
                layoutParams =  mVideoView.getLayoutParams() as RelativeLayout.LayoutParams
                /*layoutParams.leftMargin = X - xDelta
                layoutParams.topMargin = Y - yDelta*/
                mfullWin.videoLayout.layoutParams = layoutParams
                //X轴移动
                //Y轴移动
            }

        }


    }

    fun onTouchEvent(event: MotionEvent): Boolean {
// TODO Auto-generated method stub
        val X = event.rawX.toInt()
        val Y = event.rawY.toInt()
        when (event.action and MotionEvent.ACTION_MASK) {
            MotionEvent.ACTION_DOWN -> {
                val lParams = mVideoView.getLayoutParams() as RelativeLayout.LayoutParams
                xDelta = X - lParams.leftMargin
                yDelta = Y - lParams.topMargin
            }
            MotionEvent.ACTION_UP -> {
            }
            MotionEvent.ACTION_POINTER_DOWN -> {
            }
            MotionEvent.ACTION_POINTER_UP -> {
            }
            MotionEvent.ACTION_MOVE -> {
                val layoutParams = mVideoView.getLayoutParams() as RelativeLayout.LayoutParams
                layoutParams.leftMargin = X - xDelta
                layoutParams.topMargin = Y - yDelta
                mVideoView.setLayoutParams(layoutParams) //自己继承VIEW的this
            }
        }
        mVideoView.invalidate()
        return true
    }

    var mFormatBuilder = StringBuilder()
    var mFormatter: Formatter = Formatter(mFormatBuilder, Locale.getDefault())
    //将长度转换为时间
    private fun stringForTime(timeMs: Int): String? {
        val totalSeconds = timeMs / 1000
        val seconds = totalSeconds % 60
        val minutes = totalSeconds / 60 % 60
        val hours = totalSeconds / 3600
        mFormatBuilder.setLength(0)
        return if (hours > 0) {
            mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString()
        } else {
            mFormatter.format("%02d:%02d", minutes, seconds).toString()
        }
    }


}

/**
 * Created by aierJun on 2016/12/21.
 */
class MoveVideooView : VideoView {
    private var _xDelta = 0
    private var _yDelta = 0

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
// TODO Auto-generated method stub
        val X = event.rawX.toInt()
        val Y = event.rawY.toInt()
        when (event.action and MotionEvent.ACTION_MASK) {
            MotionEvent.ACTION_DOWN -> {
                val lParams = layoutParams as RelativeLayout.LayoutParams
                _xDelta = X - lParams.leftMargin
                _yDelta = Y - lParams.topMargin
            }
            MotionEvent.ACTION_UP -> {
            }
            MotionEvent.ACTION_POINTER_DOWN -> {
            }
            MotionEvent.ACTION_POINTER_UP -> {
            }
            MotionEvent.ACTION_MOVE -> {
                var layoutParams = layoutParams as RelativeLayout.LayoutParams
                layoutParams.leftMargin = X - _xDelta
                layoutParams.topMargin = Y - _yDelta
                //layoutParams.rightMargin = -250;
                //layoutParams.bottomMargin = -250;
                layoutParams = layoutParams //自己继承VIEW的this
            }
//            MotionEvent.
        }
        invalidate()
        return true
    }
}
